﻿/*========================== 
 * @author 郑金泉
 * @desc Dictionary实用工具
 * ========================= */
using System;
using System.Collections.Generic;
using System.Text;

namespace Obsidian.Utils
{
    public class DictUtil
    {

        /// <summary>
        /// 根据键值从字典获得值列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="V"></typeparam>
        /// <param name="dict">字典</param>
        /// <param name="keys">键值</param>
        /// <returns></returns>
        public static List<V> GetListByKeys<K, V>(IDictionary<K, V> dict, params K[] keys)
        {
            List<V> list = new List<V>();
            foreach (K k in keys)
            {
                if (dict.ContainsKey(k))
                    list.Add(dict[k]);
            }
            return list;
        }


        public static K[] GetDistinctKeys<K, V>(IDictionary<K, V> dict)
        {
            K[] arr = new K[dict.Count];
            int i = 0;
            foreach (KeyValuePair<K, V> pair in dict)
            {
                arr[i] = pair.Key;
                i++;
            }
            return arr;
        }

        public static string GetKeysString<K, V>(IDictionary<K, V> dict, string separator)
        {
            StringBuilder sb = new StringBuilder();
            bool first = true;
            foreach (KeyValuePair<K, V> pair in dict)
            {
                if (first) first = false;
                else sb.Append(separator);
                sb.Append(pair.Key);
            }
            return sb.ToString();
        }

        public static string ToString<K, V>(IDictionary<K, V> dict, string separator = "&", string keyValueSeparator = "=")
        {
            StringBuilder sb = new StringBuilder();
            bool first = true;
            foreach (KeyValuePair<K, V> pair in dict)
            {
                if (first) first = false;
                else sb.Append(separator);
                sb.Append(Convert.ToString(pair.Key));
                sb.Append(keyValueSeparator);
                sb.Append(Convert.ToString(pair.Value));
            }
            return sb.ToString();
        }

    }
}
